package my.netty.channel.handler;

import my.netty.channel.ChannelPipeline;

import java.io.IOException;

public abstract class AbstractChannelHandlerContext {

    private final ChannelPipeline pipeline;

    public AbstractChannelHandlerContext next;
    public AbstractChannelHandlerContext prev;

    public AbstractChannelHandlerContext(ChannelPipeline pipeline) {
        this.pipeline = pipeline;
    }

    public ChannelPipeline pipeline() {
        return pipeline;
    }

    public void fireChannelRead(final Object msg) {
        AbstractChannelHandlerContext ctx = this;
        do {
            ctx = ctx.next;
        } while (!(ctx.handler() instanceof ChannelInboundHandler));
        ((ChannelInboundHandler) ctx.handler()).channelRead(ctx, msg);
    }

    public void fireWriteAndFlush(final Object msg) throws IOException {
        AbstractChannelHandlerContext ctx = this;
        do {
            ctx = ctx.prev;
        } while (!(ctx.handler() instanceof ChannelOutboundHandler));
        ((ChannelOutboundHandler) ctx.handler()).writeAndFlush(ctx, msg);
    }

    public abstract ChannelHandler handler();
}
